<template>
  <el-dialog title="数据导入" v-model="dialogVisible" width="400" @close="dialogVisible = false">
    <el-upload
      ref="excelUpload"
      class="upload-excel"
      :action="uploadExcelUrl"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-exceed="handleExceed"
      :on-error="handleUploadError"
      :headers="headers"
      :auto-upload="false"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>

      <el-button class="ml-3" type="success" @click="submitUpload">
        上传文件
      </el-button>

      <template #tip>
        <div class="el-upload__tip">
          上传文件仅支持，xls/xlsx格式，文件大小不得超过1M
        </div>
      </template>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { getToken } from "@/utils/auth";
import { getCurrentInstance } from 'vue';

const excelUpload = ref()
const submitUpload = () => {
  excelUpload.value.submit()
}

  // 弹窗显示状态
  const dialogVisible = ref(false)

const props = defineProps({
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
  // api 地址
  apiUrl: {
    type: String,
    default: "",
  }
})

const { proxy } = getCurrentInstance();
const emit = defineEmits(['success']);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadExcelUrl = ref(import.meta.env.VITE_APP_BASE_API + props.apiUrl); // 上传的excel文件到服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("excel文件上传成功");
    dialogVisible.value = false
    emit('success')
  } else {
    proxy.$modal.msgError(res.msg);
  }
  proxy.$modal.closeLoading();
  excelUpload.value.clearFiles()
}

// 上传失败
function handleUploadError() {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传excel文件失败");
}

// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  }
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传excel文件，请稍候...");
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 开启对话框
const openDialog = () => {
  dialogVisible.value = true
}

defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
</style>